﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Microsoft.SqlServer.Management.Smo;
using Chi.Lib.DBHelper;
using System.Diagnostics;

public partial class Module_ui_DBTree : System.Web.UI.UserControl
{
    Database db;
    Server server;
    protected void Page_Load(object sender, EventArgs e)
    {

        if (!IsPostBack)
        {
            CreateDBTree();
        }
    }

    public void CreateDBTree()
    {
        if (Session[SessionKey.TBTreeNode] == null &&
            Session[SessionKey.ViewTreeNode] == null &&
            Session[SessionKey.SPTreeNode] == null )
        {
            server = DBHelperSMO.GetServerInstance();
            db = DBHelperSMO.GetDBInstance();
           
        }
        this.TreeView1.Nodes.Add(CreateTBTreeViewNode());
        this.TreeView1.Nodes.Add(CreateViewTreeNode());
        this.TreeView1.Nodes.Add(CreateSPTreeNode());
        
    }

    public TreeNode CreateTBTreeViewNode()
    {
        if (Session[SessionKey.TBTreeNode] != null)
        {
            return (TreeNode)Session[SessionKey.TBTreeNode];
        }

        TreeNode parentNode = new TreeNode();
        parentNode.Value = "Base Table";
        parentNode.Text = string.Format("Table ({0})", db.Tables.Count);

        #region Insert Node
        // 直接跑db.Tables的迴圈會因為時間太久而發生錯誤
        // 先暫存到tbs，從tbs去跑迴圈反而不會發生錯誤
        // 錯誤不是每次都會發生...
        // Microsoft.SqlServer.Management.Smo.TableCollection tbs = db.Tables;

        foreach (Microsoft.SqlServer.Management.Smo.Table tb in db.Tables)
        {
            TreeNode childNode = new TreeNode(tb.Name, tb.ID.ToString());
            foreach (Column col in tb.Columns)
            {
                TreeNode colNode = new TreeNode();
                colNode.Value = col.ID.ToString();
                colNode.Text = string.Format("{0} ({1}{2}({3}), {4})",
                                        col.Name,
                                        col.InPrimaryKey ? "PK, " : "",
                                        col.DataType.Name,
                                        col.DataType.MaximumLength.ToString(),
                                        col.Nullable ? "Null" : "Non Null");

                childNode.ChildNodes.Add(colNode);
            }//end foreach columns

            childNode.NavigateUrl = "~/ShowTableSchemaSMO.aspx?menu=" + parentNode.Text
                                    + "&tbName=" + childNode.Text
                                    + "&tb=" + childNode.Value
                                    + "&id=" + childNode.Value;
            parentNode.ChildNodes.Add(childNode);
        }//end foreach tables
        
        #endregion
        Session[SessionKey.TBTreeNode] = parentNode;
        return (TreeNode)Session[SessionKey.TBTreeNode];
    }

    public TreeNode CreateViewTreeNode()
    {
        if (Session[SessionKey.ViewTreeNode] != null)
        {
            return (TreeNode)Session[SessionKey.ViewTreeNode];
        }

        TreeNode parentNode = new TreeNode();
        int viewcount = 0;
        parentNode.Value = "View";

        #region Insert Node

        foreach (Microsoft.SqlServer.Management.Smo.View vi in db.Views)
        {
            if (vi.Schema != "dbo")
            {
                continue;
            }
            TreeNode childNode = new TreeNode(vi.Name, vi.ID.ToString());

            foreach (Column col in vi.Columns)
            {
                TreeNode colNode = new TreeNode();
                colNode.Value = col.ID.ToString();
                colNode.Text = col.Name;
                childNode.ChildNodes.Add(colNode);
            }//end foreach columns

            childNode.NavigateUrl = "~/ShowTableSchemaSMO.aspx?menu=" + parentNode.Text
                                    + "&ViewName=" + childNode.Text;

            parentNode.ChildNodes.Add(childNode);
            viewcount++;
        }//end foreach tables

        #endregion

        parentNode.Text = string.Format("View ({0})", viewcount);
        Session[SessionKey.ViewTreeNode] = parentNode;
        return (TreeNode)Session[SessionKey.ViewTreeNode];
    }

    public TreeNode CreateSPTreeNode()
    {
        if (Session[SessionKey.SPTreeNode] != null)
        {
            return (TreeNode)Session[SessionKey.SPTreeNode];
        }

        TreeNode parentNode = new TreeNode();
        int spcount = 0;
        parentNode.Value = "Stored Procedure";

        #region Insert Node

        foreach (Microsoft.SqlServer.Management.Smo.StoredProcedure sp in db.StoredProcedures)
        {
            if (sp.Schema != "dbo")
            {
                continue;
            }
            TreeNode childNode = new TreeNode(sp.Name, sp.ID.ToString());

            //foreach (Column col in sp.Columns)
            //{
            //    TreeNode colNode = new TreeNode();
            //    colNode.Value = col.ID.ToString();
            //    colNode.Text = col.Name;
            //    childNode.ChildNodes.Add(colNode);
            //}//end foreach columns

            childNode.NavigateUrl = "~/ShowCommandSMO.aspx?menu=" + parentNode.Text
                                    + "&SPName=" + childNode.Text;

            parentNode.ChildNodes.Add(childNode);
            spcount++;
        }//end foreach tables

        #endregion

        parentNode.Text = string.Format("Stored Procedure ({0})", spcount);
        Session[SessionKey.SPTreeNode] = parentNode;
        return (TreeNode)Session[SessionKey.SPTreeNode];
    }
}
